package com.ruoyi.framework.web.service;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.ruoyi.common.core.domain.model.AppRegisterBody;
import com.ruoyi.common.utils.*;
import com.ruoyi.common.utils.uuid.IdUtils;
import com.ruoyi.system.domain.MyKernelUserEqu;
import com.ruoyi.system.domain.SysUserRole;
import com.ruoyi.system.mapper.SysUserRoleMapper;
import com.ruoyi.system.service.ISysUserEquService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.ruoyi.common.constant.CacheConstants;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.RegisterBody;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.exception.user.CaptchaException;
import com.ruoyi.common.exception.user.CaptchaExpireException;
import com.ruoyi.framework.manager.AsyncManager;
import com.ruoyi.framework.manager.factory.AsyncFactory;
import com.ruoyi.system.service.ISysConfigService;
import com.ruoyi.system.service.ISysUserService;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * 注册校验方法
 *
 * @author ruoyi
 */
@Component
public class SysRegisterService
{
    @Autowired
    private ISysUserService userService;

    @Autowired
    private ISysConfigService configService;

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private ISysUserEquService iSysUserEquService;

    @Autowired
    private SysUserRoleMapper userRoleMapper;

    /**
     * 新增用户角色信息
     *
     * @param userId 用户ID
     * @param roleIds 角色组
     */
    public void insertUserRole(Long userId, Integer[] roleIds)
    {
        if (StringUtils.isNotEmpty(roleIds))
        {
            // 新增用户与角色管理
            List<SysUserRole> list = new ArrayList<SysUserRole>(roleIds.length);
            for (Integer roleId : roleIds)
            {
                SysUserRole ur = new SysUserRole();
                ur.setUserId(userId);
                ur.setRoleId(roleId.longValue());
                list.add(ur);
            }
            userRoleMapper.batchUserRole(list);
        }
    }
    /**
     * 注册
     */
    public String register(RegisterBody registerBody) throws Exception {
        String msg = "", username = registerBody.getUsername(), password = registerBody.getPassword();
        password = RsaUtilClient.decryptByPrivateKey("",password);

        boolean captchaEnabled = configService.selectCaptchaEnabled();
        //电脑自带的验证码
        String code =registerBody.getCode();
        //系统标识：1：电脑  2：手机  3：设备
        int sysFlag = registerBody.getSysFlag();
        //用户别名
        String nickName = registerBody.getNickName();
        //sn 码  用于绑定设备用
        String snCode = registerBody.getSnCode();
        //销售渠道  用于绑定设备用
        String saleNel = registerBody.getSaleNel();
        //手机验证码
        String telCode =registerBody.getTelCode();

        Integer[] rl = registerBody.getRoleIds();

        // 验证码开关
        if (captchaEnabled&&StringUtils.isNotEmpty(code))
        {
            validateCaptcha(username, code, registerBody.getUuid());
        }

        if (StringUtils.isEmpty(username))
        {
            msg = "用户名不能为空";
        }
        else if (StringUtils.isEmpty(password))
        {
            msg = "用户密码不能为空";
        }
        else if (username.length() < UserConstants.USERNAME_MIN_LENGTH
                || username.length() > UserConstants.USERNAME_MAX_LENGTH)
        {
            msg = "账户长度必须在2到20个字符之间";
        }
        else if (password.length() < UserConstants.PASSWORD_MIN_LENGTH
                || password.length() > UserConstants.PASSWORD_MAX_LENGTH)
        {
            msg = "密码长度必须在5到20个字符之间";
        }
        else if (UserConstants.NOT_UNIQUE.equals(userService.checkUserNameUnique(username)))
        {
            msg = "保存用户'" + username + "'失败，注册账号已存在";
        }
        else
        {
            SysUser sysUser = new SysUser();
            sysUser.setUserName(username);
            sysUser.setPhonenumber(username);
            if(StringUtils.isNotEmpty(nickName)){
                sysUser.setNickName(nickName);
            }
            String jpas =  SecurityUtils.encryptPassword(password);
            sysUser.setPassword(jpas);
            //是哪个设备端注册的
            if(StringUtils.isNotEmpty(String.valueOf(sysFlag))){
                sysUser.setSysFlag(sysFlag);
            }
            //去注册用户
            boolean regFlag = userService.registerUser(sysUser);
            if(rl.length>0){
                this.insertUserRole(sysUser.getUserId(),registerBody.getRoleIds());
            }

            if (!regFlag)
            {
                msg = "注册失败,请联系系统管理人员";
            }
            else
            {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.REGISTER,
                        MessageUtils.message("user.register.success")));
            }
        }
        return msg;
    }

    /**
     * 校验验证码
     *
     * @param username 用户名
     * @param code 验证码
     * @param uuid 唯一标识
     * @return 结果
     */
    public void validateCaptcha(String username, String code, String uuid)
    {
        String verifyKey = CacheConstants.CAPTCHA_CODE_KEY + StringUtils.nvl(uuid, "");
        String captcha = redisCache.getCacheObject(verifyKey);
        redisCache.deleteObject(verifyKey);
        if (captcha == null)
        {
            throw new CaptchaExpireException();
        }
        if (!code.equalsIgnoreCase(captcha))
        {
            throw new CaptchaException();
        }
    }


    public String appRegister(AppRegisterBody user) throws Exception {
        String msg = "", username = user.getUsername(), password = user.getPassword(),sex = user.getSex(),birthday = user.getBirthday();
        if(StrUtil.isNotEmpty(password)){
            //解密-此处是明文
            password = RsaUtilClient.decryptByPrivateKey("",password);
            if (password.length() < UserConstants.PASSWORD_MIN_LENGTH
                    || password.length() > UserConstants.PASSWORD_MAX_LENGTH)
            {
                msg = "密码长度必须在5到20个字符之间";
            }
        }
        String userType = user.getUserType();
        //省
        String province = user.getProvince();
        //市
        String city = user.getCity();
        //区
        String area = user.getArea();
        //密保问题
        String question = user.getQuestion();
        //资格证书
        String url = user.getUrl();

        boolean captchaEnabled = configService.selectCaptchaEnabled();
        //电脑验证码
        String code =user.getCode();
        //系统标识：1：电脑  2：手机  3：设备
        int sysFlag = user.getSysFlag();
        //用户别名
        String nickName = user.getNickName();
        //sn 码  用于绑定设备用
        String snCode = user.getSnCode();

        Integer[] rl = user.getRoleIds();

        // 验证码开关
        if (captchaEnabled&&StringUtils.isNotEmpty(code))
        {
            validateCaptcha(username, code, user.getUuid());
        }

        if (StringUtils.isEmpty(username))
        {
            msg = "用户名不能为空";
        }
        else if (username.length() < UserConstants.USERNAME_MIN_LENGTH
                || username.length() > UserConstants.USERNAME_MAX_LENGTH)
        {
            msg = "账户长度必须在2到20个字符之间";
        }

        else if (UserConstants.NOT_UNIQUE.equals(userService.checkUserNameUnique(username)))
        {
            msg = "注册账号已存在";
        }
        else
        {
            SysUser sysUser = new SysUser();
            sysUser.setUserName(username);
            if(StringUtils.isNotEmpty(nickName)){
                sysUser.setNickName(nickName);
            }
            //省id
            if(StrUtil.isNotEmpty(province)){
                sysUser.setProvince(province);
            }
            //市id
            if(StrUtil.isNotEmpty(city)){
                sysUser.setCity(city);
            }
            //区id
            if(StrUtil.isNotEmpty(area)){
                sysUser.setArea(area);
            }
            //经度
            if(StrUtil.isNotEmpty(user.getLgt())){
                sysUser.setLgt(user.getLgt());
            }
            //纬度
            if(StringUtils.isNotEmpty(user.getLat())){
                sysUser.setLat(user.getLat());
            }
            if(StringUtils.isNotEmpty(birthday)){
                sysUser.setRemarkTwo(birthday);
            }
            if(StringUtils.isNotEmpty(question)){
                sysUser.setQuestion(question);
            }
            if(StringUtils.isNotEmpty(url)){
                sysUser.setUrl(url);
            }
            if(StringUtils.isNotEmpty(password)){
                //加密
                String jpas =  SecurityUtils.encryptPassword(password);
                sysUser.setPassword(jpas);
            }else {
                String jps =  SecurityUtils.encryptPassword("kenuo1@23");
                sysUser.setPassword(jps);
            }
            //是哪个设备端注册的
            if(StringUtils.isNotEmpty(String.valueOf(sysFlag))){
                sysUser.setSysFlag(sysFlag);
            }else {
                sysUser.setSysFlag(2);
            }
            //手机类型--userType  用户类型（00系统用户 02app医生用户 03患者用户）
            if (StringUtils.isNotEmpty(userType)){
                sysUser.setUserType(userType);
            }else{
                sysUser.setUserType("02");
            }

            //去注册用户
            boolean regFlag = userService.registerUser(sysUser);
            if(ObjectUtil.isNotNull(rl)){
                this.insertUserRole(sysUser.getUserId(),user.getRoleIds());
            }

            if (!regFlag)
            {
                msg = "注册失败,请联系系统管理人员";
            }
            else
            {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.REGISTER,
                        MessageUtils.message("user.register.success")));
            }
        }
        return msg;
    }

}
